﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using cz.muni.fi.pb138.Sessions;

namespace cz.muni.fi.pb138
{
    public partial class RegisterForm : Form
    {
        public RegisterForm()
        {
            InitializeComponent();
        }

		/// <summary>
		/// cancel button hit, no special action happens, only the window is closed with a <c>Cancel</c> result
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

		/// <summary>
		/// The Register button is hit. Registers new user in the DB if both passwords are the same,
		/// and if the user with the same name doesn't already exist
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void loginButton_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.loginBox.Text) || String.IsNullOrEmpty(this.passBox.Text) || String.IsNullOrEmpty(this.passBox2.Text))
            {
                MessageBox.Show("Please enter all login details","Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (!this.passBox.Text.Equals(this.passBox2.Text))
            {
                MessageBox.Show("Entered passwords are not the same !", "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.loginBox.Text == "users" || this.loginBox.Text == "Users")
            {
                MessageBox.Show("Please choose different name!");
                return;
            }

            if (!AdminSession.HasServerConnection())
            {
                MessageBox.Show("Failed to connect server!", "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            using(QuerySession s = new QuerySession())
	        {
                if (s.UserExists(this.loginBox.Text))
                {
                    MessageBox.Show("Please choose different name!");
                    return;
                }
            }

            using (AdminSession s = new AdminSession())
            {
                try
                {
                    s.StoreUser(this.loginBox.Text, this.passBox.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                }                        

            }
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}
